package com.xukai.springboot.service.statistics;

import com.xukai.springboot.datalayer.statis.StatisDataMapper;
import com.xukai.springboot.entity.statistics.t_statis_data;
import com.xukai.springboot.util.config.DatabaseContextHolder;
import com.xukai.springboot.util.constants.DataBaseType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 统计数据服务
 */
@Service
public class StatisDataService {

    /**
     * 数据统计Mapper
     */
    @Autowired
    StatisDataMapper statisDataMapper;

    /**
     * 根据数据源ID获取数据
     */
    public t_statis_data GetDataByDataSourceID(int dataSourceID) {
        DatabaseContextHolder.setDB(DataBaseType.manager.name());
        return statisDataMapper.GetStatisData(dataSourceID);
    }

    /**
     * 判断统计数据是否存在
     */
    public boolean isExist(int dataSourceID) {
        DatabaseContextHolder.setDB(DataBaseType.manager.name());
        boolean result = false;
        int count = statisDataMapper.GetStatisDataCount(dataSourceID);
        if (count > 0) {
            result = true;
        }
        return result;
    }

    /**
     * 新建统计数据
     */
    public t_statis_data AddStatisData(String dataStr, int dataSourceID) {
        DatabaseContextHolder.setDB(DataBaseType.manager.name());
        t_statis_data data = new t_statis_data();
        Date currentDate = new Date();
        data.setCreateTime(currentDate);
        data.setData(dataStr);
        data.setDataSourceID(dataSourceID);
        data.setLastUpdateTime(currentDate);
        statisDataMapper.AddStatisDataCount(data);
        return data;
    }

    /**
     * 更新统计数据
     */
    public void UpdateStatisData(String dataStr, int dataSourceID) {
        DatabaseContextHolder.setDB(DataBaseType.manager.name());
        statisDataMapper.UpdateStatisData(dataStr, new Date(), dataSourceID);
    }


    public void saveData(String dataStr, int dataSourceID) {
        DatabaseContextHolder.setDB(DataBaseType.manager.name());
        //判断数据是否存在
        if (isExist(dataSourceID)) {
            UpdateStatisData(dataStr, dataSourceID);
        } else {
            AddStatisData(dataStr, dataSourceID);
        }

    }
}
